<?php

namespace App\Models\Workflow;

use App\Enums\Workflow\WorkflowEnum;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use App\Service\WorkOrder\WorkOrderBaseService;
use Illuminate\Database\Eloquent\Relations\HasMany;

class WorkflowOrderModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'workflow_orders';

    protected $fillable = [
        'workflowNo',
        'name',
        'workflowType',
        'status',
        'shopId',
        'relationId',
        'isDeleted',
        'createdByUid',
    ];

    const STATUS_ING    = 0;
    const STATUS_FINISH = 1;
    const STATUS_CLOSE  = 2;

    const STATUS_TEXT = [
        self::STATUS_FINISH => '已完成',
        self::STATUS_ING    => '进行中',
        self::STATUS_CLOSE  => '已关闭',
    ];

    public function nodesRel(): HasMany
    {
        return $this->hasMany(WorkflowOrderNodeModel::class, 'workflowOrderId', 'id');
    }

    public function logsRel(): HasMany
    {
        return $this->hasMany(WorkflowOrderLogModel::class, 'workflowOrderId', 'id');
    }

    /**
     * 获取当前工单的自定义节点状态
     * @return string
     */
    public function nodeDefineStatusText(): string
    {
        $currentMainNode = $this->nodesRel->where('status', WorkflowOrderNodeModel::STATUS_ING)->first();
        if (!$currentMainNode) {
            return '已完成';
        }

        $text = '';

        switch ($currentMainNode->businessType) {
            case  WorkflowEnum::BUSINESS_TYPE_SUBMIT_APPLY:
                $text = '待提交';
                break;
            case WorkflowEnum::BUSINESS_TYPE_FIX_AUDIT:
                if ($currentMainNode->handlerType == WorkflowEnum::HANDLER_TYPE_HEAD) {
                    $text = '待复审';
                } elseif ($currentMainNode->handlerType == WorkflowEnum::HANDLER_TYPE_PROVINCE) {
                    $text = '待初审';
                } elseif ($currentMainNode->handlerType == WorkflowEnum::HANDLER_TYPE_SUPERVISE) {
                    $text = '待初审';
                }

                break;
            case WorkflowEnum::BUSINESS_TYPE_RENEW_SIGN:
                $text = '待签署';
                break;
        }

        return $text;
    }

    // 生成工单号
    public static function generateWorkflowNo(): string
    {
        return "GD" . date('YmdHis') . str_pad(WorkOrderBaseService::autoincrementByRedis('GD'), 4, "0", STR_PAD_LEFT);
    }
}
